package org.csu.demo.nio_chat.clientwithWeb;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class ChatClient {
    private SocketChannel socketChannel;
    private Selector selector;
    private Charset charset = Charset.forName("UTF-8");
    private List<String> messages = new ArrayList<>();

    public ChatClient() {
        try {
            // 连接服务器
            socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 83));
            // 接受服务端响应数据
            selector = Selector.open();
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
            // 创建线程
            new Thread(new ClientThread(selector, messages)).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendMessage(String name, String msg) {
        try {
            if (msg != null && msg.length() > 0) {
                // 将消息发送到服务器
                socketChannel.write(charset.encode(name + ": " + msg));
                // 将消息添加到本地消息列表
                messages.add(name + ": " + msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public List<String> getMessages() {
        return messages;
    }
}